/*************************************************************************
	> File Name: tcp_client.cc
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/10/03 16:33
 ************************************************************************/

#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

const int BUF_SIZE = 1024;

uint16_t serverport;
std::string serverip;

static void usage(std::string proc)
{
    std::cout << "\nUsage:" << proc << " ip port\n" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3) {
        usage(argv[0]);
        exit(1);
    }
    serverip = argv[1];
    serverport = atoi(argv[2]);
    bool alive = false;
    int sock = 0;
    std::string message;
    char buffer[BUF_SIZE];
    while (1) {
        memset(buffer, 0, sizeof buffer);
        if (!alive) {
            if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
                std::cout << "socket error, " << errno << strerror(errno) << std::endl;
            }
            struct sockaddr_in server;
            memset(&server, 0, sizeof server);
            server.sin_family = AF_INET;
            server.sin_port = htons(serverport);
            server.sin_addr.s_addr = inet_addr(serverip.c_str());
            if (connect(sock, (struct sockaddr*)&server, sizeof server) < 0) {
                std::cerr << "connect error" << std::endl;
                exit(3);
            }
            std::cout << "connect success" << std::endl;
            alive = true;
        }
        std::cout << "Please input your word" << std::endl;
        std::getline(std::cin, message);
        if ("quit" == message) {
            break;
        }
        ssize_t s = send(sock, message.c_str(), message.size(), 0);
        if (s > 0) {
            if (recv(sock, buffer, sizeof buffer - 1, 0) > 0) {
                std::cout << "In Chinese:" << buffer << std::endl;
            } else {
                alive = false;
                close(sock);
            }
        } else {
            alive = false;
            close(sock);
        }
    }
    return 0;
}
